layui.use(['table', 'admin', 'ax', 'laydate','layer','element'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var layer = layui.layer;
    var element = layui.element;
    laydate.render({
        elem:'#peisongTime'
        ,value:new Date()
    });

        $.ajax({
            url: "/hxCollectingCenter/cha",
            success: function(data) {
                var result = layui.$.map(data, function(item) {
                    return { "locationId": item.locationId,"location": item.location,"stockPortId":item.stockPortId,"stockPort": item.stockPort,"status": item.status,"getUnit": item.getUnit,"trayId":item.trayId,"trayNumber":item.trayNumber};
                });
                var channels = {};
                result.forEach(function(item) {
                    var channel = "H"+("000"+item.stockPort).substr(-3)+"通道";
                    if (!channels[channel]) {
                        channels[channel] = [];
                    }
                    channels[channel].push(item);
                });
                var html = '';
                Object.keys(channels).forEach(function(channel) {
                    var items = channels[channel];
                    var rows = Math.ceil(items.length / 3);
                    var gridTemplateAreas = '';
                    for (var i = 0; i < rows; i++) {
                        gridTemplateAreas += `"${channel}-${i+1}-1 ${channel}-${i+1}-2 ${channel}-${i+1}-3}"\n`;
                    }
                    html += `<div style="border: thin dotted darkseagreen;">\n`;
                    let hasDisplayed = false;
                    for (const item of items) {
                        if (!hasDisplayed) {
                            const getUnit = item.getUnit;
                            // 在第一次循环中显示 getUnit 信息
                            html += `<div class="layui-row layui-col-space12">\n`;
                                html += `<div class="layui-col-md4">\n`;
                                    html += `<span style="color: #000000;font-weight: 600;"class="channel-name" >${channel}</span>\n`;
                                html += `</div>\n`;
                                html += `<div class="layui-col-md2">\n`;
                                html += `<button id="id-${item.stockPort}" name="zhuidan">追单</button>\n`;
                                html += `</div>\n`;
                                html += `<div class="layui-col-md2">\n`;
                                html += `<button id="id-${item.stockPort}" name="yijianzhuanyi">全移</button>\n`;
                                html += `</div>\n`;
                                html += `<div class="layui-col-md2">\n`;
                                html += `<button id="id-${item.stockPort}" name="zhuanyi" >单移</button>\n`;
                                html += `</div>\n`;
                                html += `<div class="layui-col-md2">\n`;
                                html += `<button id="id-${item.stockPort}" name="chongfen" >重分</button>\n`;
                                html += `</div>\n`;
                            html += `</div>\n`;
                            html += `<div>\n`;
                                html += `<div class="layui-row layui-col-space10">\n`;
                                    html += `<div class="layui-col-md12">\n`;
                                    html += `门店：${getUnit}\n`;
                                    html += `</div>\n`;
                                html += `</div>\n`;
                            html += `</div>\n`;
                            hasDisplayed = true;
                        }
                    }
                    // html += `<div class="channel-name">${channel}-${item.getUnit}</div>\n`;
                    html += `<div class="layui-row layui-col-space10">\n`;
                    html += `<div class="layui-col-md12">\n`;
                    items.forEach(function(item, index) {
                        var row = Math.floor(index / 3) + 1;
                        var col = index % 3 + 1;
                        var itemClass = 'item';
                        var locationClass = 'location';

                        if (item.status === '已分配') {
                            itemClass += ' allocated';
                            locationClass += ' allocated';
                            html += `<span class="layui-badge layui-bg-blue">配</span>\n`;
                        } else if (item.status === '已占用') {
                            itemClass += ' occupied';
                            locationClass += ' occupied';
                            html += `<span class="layui-badge layui-bg-red">占</span>\n`;
                        }else{
                            html += `<span class="layui-badge layui-bg-cyan">空</span>\n`;
                        }
                    });
                    html += `</div>\n`;
                    html += `</div>\n`;
                    html += `</div>\n`;
                });
                 // 将生成的 HTML 插入到页面中
                document.getElementById('collectionContainer').innerHTML = html;
                const   zhuanyis = document.getElementsByName('zhuanyi');
                for (const  element of zhuanyis) {
                    element.addEventListener('click', function() {
                        let id = this.id;
                        layer.open({
                            type: 2,
                            title: '门店转移',
                            area: ['1100px', '500px'],
                            anim: 5,
                            content: '/hxCollectingCenter/edit?stockPort=' + id,
                        });
                    });
                };

                const  zhuidans = document.getElementsByName('zhuidan');
                for (const  element of zhuidans) {
                    element.addEventListener('click', function() {
                        let id = this.id;
                        var operation = function () {
                            var ajax = new $ax(Feng.ctxPath + "/hxCollectingCenter/zhuijia", function (data) {
                                if(data.success){
                                    location.reload();
                                    Feng.success("追单成功！");
                                }else{
                                    Feng.error("追单失败！" + data.message)
                                }
                            }, function (data) {
                                Feng.error("删除失败!" + data.responseJSON.message + "!");
                            });
                            ajax.set("stockPort", id);
                            ajax.start();
                        };
                        Feng.confirm("确定要追单吗?", operation);
                    });
                };

                const   yijianzhuanyis = document.getElementsByName('yijianzhuanyi');
                for (const  element of yijianzhuanyis) {
                    element.addEventListener('click', function () {
                        let id = this.id;
                        layer.open({
                            type: 2,
                            title: '门店一键转移',
                            area: ['1100px', '500px'],
                            anim: 5,
                            content: '/hxCollectingCenter/edit2?stockPort=' + id,
                        });
                    });
                };

                const   chongfen = document.getElementsByName('chongfen');
                for (const  element of chongfen) {
                    element.addEventListener('click', function () {
                        let id = this.id;
                        var operation = function () {
                            var ajax = new $ax(Feng.ctxPath + "/hxCollectingCenter/chongfen", function (data) {
                                if(data.success){
                                    location.reload();
                                    Feng.success("重新分配成功！");
                                }else{
                                    Feng.error("重新分配失败！" + data.message)
                                }
                            }, function (data) {
                                Feng.error("重新分配失败!" + data.responseJSON.message + "!");
                            });
                            ajax.set("stockPort", id);
                            ajax.start();
                        };
                        Feng.confirm("确定要重新分配吗?", operation);
                    });
                };

                const   elements = document.getElementsByClassName('layui-col-md9');
                  // 遍历所有元素并添加点击事件监听器
                for (const  element of elements) {
                    element.addEventListener('click', function() {
                        $('#collectionLocation').html('');
                        const value = this.textContent || this.innerText;
                        const channelName = this.querySelector('.channel-name').textContent.trim();
                        console.log(channelName);
                        const filteredChannelName = channelName.replace(/H/, '').replace(/通道/g, '');                        console.log(filteredChannelName);
                        const numericValue = filteredChannelName.substring(0, 3);
                        console.log(numericValue);
                        const firstChar = parseInt(numericValue, 10);
                        $.ajax({
                            url: '/hxCollectionLocation/findLocation?stockPort=' + firstChar,
                            success: function(data) {
                                var result = layui.$.map(data, function(item) {
                                    return { "location": item.location,"stockPort": item.stockPort,"status": item.status,"getUnit": item.getUnit,"trayId":item.trayId,"trayNumber":item.trayNumber};
                                });
                                var channels = {};
                                result.forEach(function(item) {
                                    var channel = item.stockPort;
                                    if (!channels[channel]) {
                                        channels[channel] = [];
                                    }
                                    channels[channel].push(item);
                                });
                                var html = '';
                                Object.keys(channels).forEach(function(channel) {

                                    var items = channels[channel];
                                    var channel = "H"+("000"+channel).substr(-3)+"通道";
                                    var rows = Math.ceil(items.length / 3);
                                    var gridTemplateAreas = '';
                                    for (var i = 0; i < rows; i++) {
                                        gridTemplateAreas += `"${channel}-${i+1}-1 ${channel}-${i+1}-2 ${channel}-${i+1}-3}"\n`;
                                    }
                                    // html += `<div class="channel" >\n`;
                                    html += `<div style="border: thin dotted darkseagreen;">\n`;
                                    let hasDisplayed = false;
                                    // 遍历每个通道的 items 数组
                                    for (const item of items) {
                                        if (!hasDisplayed) {
                                            const getUnit = item.getUnit;
                                            // // 在第一次循环中显示 getUnit 信息
                                            // html += `<div class="channel-name" id="locationid" >${channel}-${getUnit}</div> \n`;
                                            // 在第一次循环中显示 getUnit 信息
                                            html += `<div class="layui-row layui-col-space10">\n`;
                                            html += `<div class="layui-col-md9">\n`;
                                            html += `<span style="color: #000000;font-weight: 600;"class="channel-name" >${channel}</span>\n`;
                                            html += `</div>\n`;
                                            html += `</div>\n`;
                                            html += `<div>\n`;
                                            html += `<div class="layui-row layui-col-space10">\n`;
                                            html += `<div class="layui-col-md12">\n`;
                                            html += `门店：${getUnit}\n`;
                                            html += `</div>\n`;
                                            html += `</div>\n`;
                                            html += `</div>\n`;
                                            hasDisplayed = true;
                                        }
                                    }
                                    // html += `<div class="channel-name">${channel}-${item.getUnit}</div>\n`;
                                    html += `<div class="layui-row layui-col-space10">\n`;
                                    html += `<div class="layui-col-md12">\n`;
                                    items.forEach(function(item, index) {
                                        var row = Math.floor(index / 2) + 1;
                                        var col = index % 2 + 1;
                                        var itemClass = 'item';
                                        var locationClass = 'location';

                                        // if (item.status === '已分配') {
                                        //     itemClass += ' allocated';
                                        //     locationClass += ' allocated';
                                        // } else if (item.status === '已占用') {
                                        //     itemClass += ' occupied';
                                        //     locationClass += ' occupied';
                                        // }
                                        // html += `<div class="${itemClass}" style="grid-area: ${channel}-${row}-${col}">\n`;
                                        // html += `<div class="${locationClass}">${item.location}-${item.trayNumber}</div>\n`;
                                        // html += `</div>\n`;
                                        if (item.status === '已分配') {
                                            itemClass += ' allocated';
                                            locationClass += ' allocated';
                                            html += `<span class="layui-badge layui-bg-blue">配</span>\n`;
                                        } else if (item.status === '已占用') {
                                            itemClass += ' occupied';
                                            locationClass += ' occupied';
                                            html += `<span class="layui-badge layui-bg-red">${item.trayNumber}</span>\n`;
                                        }else{
                                            html += `<span class="layui-badge layui-bg-cyan">空</span>\n`;
                                        }
                                    });
                                    html += `</div>\n`;
                                    html += `</div>\n`;
                                    html += `</div>\n`;


                                    // });
                                    // html += `</div> \n`;
                                    // html += `</div>\n`;
                                });
                                // 将生成的 HTML 插入到弹出窗口中
                                $('#collectionLocation').html(html);
                            },
                            complete: function() {
                                var config = {
                                    type: 1,
                                    title: '集货位',
                                    area: ['500px', '500px'],
                                    content: $('#collectionLocation'),
                                    end: function() {
                                        $('#collectionLocation').empty();
                                      //  location.reload(); // 刷新页面
                                    }
                                };
                                layer.open(config);
                            }
                        });
                    });
                }
            }
        });

    var BasicTray = {
        tableId: "unassignedTable"
    };

    var HxStorageCenter = {
        tableId: "assignedTable"
    };
    // 监听按钮点击事件
    $('#assignBtn').click(function() {
        // 弹出层配置
        var config = {
            type: 1,
            title: '分配',
            area: ['700px', '700px'],
            content: $('#assignTemplate')
        };
        // 弹出层显示
        layer.open(config);
        table.render({
            elem: '#unassignedTable',
            url: Feng.ctxPath + '/hxStorageCenter/findHxStorageOutFenpeiBySpec',
            cols: [[
                {field: 'getUnit', sort: true, title: '门店',
                    templet: function(d){
                        var str = "";
                        if (d.stockPort != null && d.stockPort != '') {
                            str += '<span style="color: #43CF7C;">'+d.getUnit+'</span>';
                        } else {
                            str = d.getUnit
                        }
                        return str
                    }
                },
                {field: 'singleQuantity', sort: true, title: '单量',
                    templet: function(d){
                        var str = "";
                        if (d.singleQuantity != null && d.singleQuantity != '') {
                            str += '<span style="color: #43CF7C;">'+d.singleQuantity+'</span>';
                        } else {
                            str = d.singleQuantity
                        }
                        return str
                    }
                },
                {field: 'stockPort', sort: true, title: '备货口',
                    templet: function(d){
                        var str = "";
                        if (d.stockPort != null && d.stockPort != '') {
                            str += '<span style="color: #43CF7C;">'+d.stockPort+'</span>';
                        } else {
                            str = d.stockPort
                        }
                        return str
                    }
                },
                {field: 'fpstockPort', title: '<span style="color: #2b85e4;"><i class="layui-icon">&#xe716;</i> 分配，多个用英文,隔开</span>', style:'color: #2b85e4;', edit:'text'}
            ]]
        });

        // 加载已分配数据
        table.render({
            elem: '#assignedTable',
            url: Feng.ctxPath + '/hxCollectionLocation/cha',
            page: true,
            limit: 120,
            limits:[120,240,360,480,1500,5000],
            cols: [[
                {type: 'checkbox'},
                {field: 'id', hide: true, title: '主键id'},
                {field: 'stockPort', sort: true, title: '通道编号'},
                {field: 'getUnit', sort: true, title: '门店'},
                {field:'操作',title:'操作',toolbar:'#tableBar'}
            ]]
        });
        // 监听切换框点击事件
        element.on('tab(assignTab)', function(){
            var index = $(this).attr('lay-id');
            if (index === '0') {
                // 切换到未分配
                table.reload('unassignedTable');
            } else if (index === '1') {
                // 切换到已分配
                table.reload('assignedTable');
            }
        });
        /**
         * 点击查询按钮
         */
        $("#btnSearch111").click(function () {
            var queryData = {};
            queryData['peisongTime'] = $("#peisongTime").val();
            queryData['condition'] = $("#condition").val();
            console.log(queryData);
            table.reload(BasicTray.tableId, {
                where: queryData, page: {curr: 1},
                done:function () {
                }
            });
        });

    });

// 添加通道
    $("#addButton").click(function () {
        var val = $("#rangerid").val();
        var locationid = $("#locationid").val();
        if (val === '' || locationid === '') {
            // 如果其中一个值为空，则提示信息
            Feng.success("请输入正确的添加信息！");
        } else {
            console.log(val);
            console.log(locationid);
            $.ajax({
                url:  Feng.ctxPath + "/hxCollectingCenter/insertstockPort?stockports="+$("#rangerid").val()+"&locations="+locationid,
                type: 'POST',
                success: function(response){
                    console.log(response);
                    location.reload();
                },
                error: function(xhr, status, error){
                    console.error(error);
                }
            });
        }
    });



    table.on('edit(' + BasicTray.tableId + ')', function (obj) {
        var data = obj.data;
        var value = obj.value;//修改后
        var field = obj.field;
        if(field == 'fpstockPort'){
            var ajax = new $ax(Feng.ctxPath + "/hxCollectingCenter/fpstockPort?getUnitId="+data.getUnitId+"&getUnit="+data.getUnit.replace(/#/g,'%23')+"&stockPorts="+value+"&singleQuantity="+data.singleQuantity, function (data) {
                if (data.success) {
                    table.reload(BasicTray.tableId);
                    Feng.success("分配成功!");
                    table.reload(HxStorageCenter.tableId);
                    location.reload();
                } else {
                    Feng.error("分配失败！"+data.message);
                }
            }, function (data) {
                Feng.error("分配失败!" + data.responseJSON.message + "!");
            });
            ajax.start();
        }
    });

    // 工具条点击事件
    table.on('tool(' + HxStorageCenter.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        console.log(data);
        if (layEvent === 'edit') {
            // HxStorageCenter.openEditDlg(data);
            var ajax = new $ax(Feng.ctxPath + "/hxCollectionLocation/clear?stockPort=" + data.stockPort ,function (data) {
                if (data.success) {
                    Feng.success("清空成功!");
                    table.reload(HxStorageCenter.tableId);
                    location.reload();
                } else {
                    Feng.error("清空失败！"+data.message);
                }
            }, function (data) {
                Feng.error("清空失败!" + data.responseJSON.message + "!");
            });
            ajax.start()
        } else if (layEvent === 'delete') {
            HxStorageCenter.onDeleteItem(data);
        }
    });
    HxStorageCenter.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/hxStorageCenter/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(HxStorageCenter.tableId);
                location.reload();
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    /**
     * 管理
     */
    var HxCollectingCenter = {
        tableId: "hxCollectingCenterTable"
    };
    var HxCollectionLocation = {
        tableId: "hxCollectionLocationTable"
    };
    /**
     * 初始化表格的列
     */
    HxCollectingCenter.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'stockPort', sort: true, title: '通道编号'},
            {field: 'getUnit', sort: true, title: '收货客户'},
            {field: 'status', title: '状态', templet: '#statusTpl'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    HxCollectingCenter.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        table.reload(HxCollectingCenter.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
                 // 搜索按钮点击事件
                 $('#btnSearch').click(function () {
                     HxCollectingCenter.search();
                 });
                 // 添加按钮点击事件
                 $('#btnAdd').click(function () {
                     HxCollectingCenter.openAddDlg();
                 });
                 // 导出excel
                 $('#btnExp').click(function () {
                     HxCollectingCenter.exportExcel();
                 });
            }
        });
    };

    /**
     * 弹出添加对话框
     */
    HxCollectingCenter.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/hxCollectingCenter/add';
    };

    /**
     * 导出excel按钮
     */
    HxCollectingCenter.exportExcel = function () {
        var checkRows = table.checkStatus(HxCollectingCenter.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    HxCollectingCenter.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/hxCollectingCenter/edit?id=' + data.id;
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    HxCollectingCenter.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/hxCollectingCenter/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(HxCollectingCenter.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + HxCollectingCenter.tableId,
        url: Feng.ctxPath + '/hxCollectingCenter/list',
        page: true,
        limit: 20,
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: HxCollectingCenter.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        HxCollectingCenter.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        HxCollectingCenter.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        HxCollectingCenter.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + HxCollectingCenter.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            HxCollectingCenter.openEditDlg(data);
        } else if (layEvent === 'delete') {
            HxCollectingCenter.onDeleteItem(data);
        }
    });
    /**
     * 初始化表格的列
     */
    HxCollectionLocation.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'location', sort: true, title: '集货位编号'},
            {field: 'stockPort', sort: true, title: '通道编号'},
            {field: 'getUnit', sort: true, title: '收货客户'},
            {field: 'status', title: '货位状态', templet: '#statusTpl'},
        ]];
    };
    // 单击行事件
    table.on('row(' + HxCollectingCenter.tableId + ')', function (obj) {
        var data = obj.data;
        $('div[lay-id="' + HxCollectingCenter.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
        $('div[lay-id="' + HxCollectingCenter.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        hxStoragePut(data);
    });

    function hxStoragePut(firstChar){
         console.log(firstChar);


        //
        // var stockPort;
        // if (firstChar!=null) {
        //     stockPort = firstChar;
        // } else {
        //     stockPort = '0';
        // }
        // // 渲染商品明细表格
        // var tableResult = table.render({
        //     elem: '#' + HxCollectionLocation.tableId,
        //     url: Feng.ctxPath + '/hxCollectionLocation/cha?stockPort=' + stockPort,
        //     page: true,
        //     limit: 30,
        //     height: 400,
        //     cellMinWidth: 100,
        //     totalRow: true ,//开启合计行
        //     cols: HxCollectionLocation.initColumn()
        // });
        //
        // /**
        //  * 点击查询按钮
        //  */
        // HxCollectionLocation.search = function () {
        //     var queryData = {};
        //     queryData['condition'] = $("#condition2").val();
        //     table.reload(HxCollectionLocation.tableId, {
        //         where: queryData, page: {curr: 1},
        //         done:function () {
        //             // 搜索按钮点击事件
        //             $('#btnSearchDetailed').click(function () {
        //                 HxCollectionLocation.search();
        //             });
        //         }
        //     });
        // };
        //
        // // 搜索按钮点击事件
        // $('#btnSearchDetailed').click(function () {
        //     HxCollectionLocation.search();
        // });

    }
});
